package com.ruoyi.web.controller.app;

import com.ruoyi.business.domain.TProduct;
import com.ruoyi.business.service.ITProductService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * App端 购物车接口
 *
 * @author laoguo
 */
@RestController
@RequestMapping("/app/cart")
public class AppCartController extends BaseController {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ITProductService productService;

    /**
     * Redis中购物车的Key
     */
    private String getCartKey() {
        // SecurityUtils.getUserId() 可以获取当前登录用户的ID
        return Constants.CART_KEY + SecurityUtils.getUserId();
    }

    /**
     * 添加商品到购物车
     */
    @PostMapping("/add")
    public AjaxResult add(@RequestBody Map<String, Object> params) {
        Long productId = Long.valueOf(params.get("productId").toString());
        Integer quantity = Integer.valueOf(params.get("quantity").toString());

        if (productId == null || quantity == null || quantity <= 0) {
            return AjaxResult.error("参数错误");
        }

        // 检查商品是否存在且已上架
        TProduct product = productService.selectTProductByProductId(productId);
        if (product == null || !"0".equals(product.getStatus())) {
            return AjaxResult.error("商品不存在或已下架");
        }

        String cartKey = getCartKey();
        // 获取购物车中已有的数量
        Integer oldQuantity = redisCache.getCacheMapValue(cartKey, productId.toString());
        if (oldQuantity == null) {
            oldQuantity = 0;
        }

        // 计算新数量并存入Redis
        int newQuantity = oldQuantity + quantity;
        redisCache.setCacheMapValue(cartKey, productId.toString(), newQuantity);

        return AjaxResult.success("添加成功");
    }

    /**
     * 获取购物车列表
     */
    @GetMapping("/list")
    public AjaxResult list() {
        String cartKey = getCartKey();
        Map<String, Integer> cartMap = redisCache.getCacheMap(cartKey);

        if (cartMap == null || cartMap.isEmpty()) {
            return AjaxResult.success(new ArrayList<>());
        }

        // 获取所有商品ID
        List<Long> productIds = cartMap.keySet().stream().map(Long::parseLong).collect(Collectors.toList());

        // 一次性从数据库查询所有商品信息
        List<TProduct> products = productService.selectTProductByProductIds(productIds);

        // 组装返回数据，将购物车中的数量和商品详细信息结合
        List<Map<String, Object>> cartItems = products.stream().map(product -> {
            Map<String, Object> item = new HashMap<>();
            item.put("productId", product.getProductId());
            item.put("productName", product.getProductName());
            item.put("coverImage", product.getCoverImage());
            item.put("price", product.getPrice());
            item.put("quantity", cartMap.get(product.getProductId().toString()));
            return item;
        }).collect(Collectors.toList());

        return AjaxResult.success(cartItems);
    }

    /**
     * 更新购物车商品数量
     */
    @PutMapping("/update")
    public AjaxResult update(@RequestBody Map<String, Object> params) {
        Long productId = Long.valueOf(params.get("productId").toString());
        Integer quantity = Integer.valueOf(params.get("quantity").toString());

        if (productId == null || quantity == null || quantity < 0) {
            return AjaxResult.error("参数错误");
        }

        String cartKey = getCartKey();
        if (quantity == 0) {
            // 如果数量为0，则删除该商品
            redisCache.deleteCacheMapValue(cartKey, productId.toString());
        } else {
            redisCache.setCacheMapValue(cartKey, productId.toString(), quantity);
        }
        return AjaxResult.success("更新成功");
    }

    /**
     * 删除购物车商品
     */
    @DeleteMapping("/remove")
    public AjaxResult remove(@RequestBody Map<String, List<Long>> params) {
        List<Long> productIds = params.get("productIds");
        if (productIds == null || productIds.isEmpty()) {
            return AjaxResult.error("请选择要删除的商品");
        }

        String cartKey = getCartKey();

        // **【核心修正】**
        // 鉴于底层的 deleteCacheMapValue 一次只能删除一个key，
        // 我们需要在这里进行循环调用。
        for (Long productId : productIds) {
            redisCache.deleteCacheMapValue(cartKey, productId.toString());
        }

        return AjaxResult.success("删除成功");
    }
}